<template lang="">
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      ></el-alert>
      <el-row>
        <el-col>
          <span>请选择商品分类：</span>
          <el-cascader
            v-model="selectValue"
            :options="cateList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children'
            }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数的面板 -->
          <el-button
            @click="openAddDialog"
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
          >
            添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="tagClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  size="small"
                  ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              lable="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                >
                  编辑
                </el-button>
                <el-button
                  @click="delParam(scope.row)"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性的面板 -->
          <el-button
            @click="openAddDialog"
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
          >
            添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="tagClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              lable="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                >
                  编辑
                </el-button>
                <el-button
                  @click="delParam(scope.row)"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog title="添加" :visible.sync="editDialogVisible" width="50%">
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //分类列表
      cateList: [],
      //被选中的分类
      selectValue: [],
      //被激活的页签名称
      activeName: 'many',
      //参数列表
      manyTableData: [],
      onlyTableData: [],
      //添加对话框开关
      addDialogVisible: false,
      addForm: {},
      //表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: blur }
        ]
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: blur }
        ]
      },
      //编辑参数对话框开关
      editDialogVisible: false,
      //编辑参数对象
      editForm: {}
    }
  },
  created() {
    this.getCatesList()
  },
  methods: {
    //获取商品分类列表
    async getCatesList() {
      //发送获取商品分类列表的网络请求
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }

      //将获取到的数据保存到本地
      // console.log(res)
      this.cateList = res.data
    },
    //联机选择器发生改变的回调
    async handleChange() {
      if (this.selectValue.length !== 3) {
        this.selectValue = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      //如果是三级分类
      this.getparamsList()
    },
    //获取数据
    async getparamsList() {
      const { data: res } = await this.$http.get(
        'categories/' + this.cateId + '/attributes',
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //tab页签点击事件处理函数
    handleTabClick() {
      // console.log(this.activeName)
      if (this.isBtnDisabled) {
        return
      }
      this.getparamsList()
    },
    //打开添加参数对话框
    openAddDialog() {
      this.addDialogVisible = true
    },
    //关闭添加参数对话框
    addDialogClose() {
      // this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    //提交添加参数请求
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
          return
        }
        //重新获取数据
        this.getparamsList()
        this.$message.success('添加成功')
        //关闭对话框
        this.addDialogVisible = false
      })
    },
    //显示编辑参数对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      this.editForm = res.data
      console.log(this.editForm)
      this.editDialogVisible = true
    },
    //提交编辑参数申请
    async editParams() {
      const {
        data: res
      } = await this.$http.put(
        `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
        { attr_name: this.editForm.attr_name, attr_sel: this.editForm.attr_sel }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      this.$message.success(res.meta.msg)
      this.getparamsList()
      this.editDialogVisible = false
    },
    //删除参数
    delParam(row) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${row.cat_id}/attributes/${row.attr_id}`
          )
          console.log(row)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            return
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getparamsList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //完成输入新的attr_val
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //发起请求
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}
`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      this.$message.success('修改参数项成功！')
    },
    //输入新的attr_val
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //删除tag
    async tagClose(i, row) {
      row.attr_vals.splice(i)
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}
`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      this.$message.success('删除参数项成功！')
    }
  },
  computed: {
    //如果按钮需要被禁用返回true
    isBtnDisabled() {
      return this.selectValue.length !== 3
    },
    cateId() {
      if (this.selectValue.length === 3) {
        return this.selectValue[2]
      }
      return null
    },
    //标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 30px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
